package com.treetao.union.core.tencent.mp;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.treetao.union.core.exception.DevMException;
import com.treetao.union.core.tencent.mp.entity.JSSDKSignResult;
import com.treetao.union.core.tencent.mp.kit.MpAccessTokenSevice;
import com.treetao.union.core.tencent.mp.kit.MpJsticketService;
import com.treetao.union.core.util.RandomUtils;

/**
 * 微信JSSDK相关服务
 * @author Dev.M
 *
 */
@Component
public class TencentJSSDKService {
	@Autowired
	private MpAccessTokenSevice mpAccessTokenSevice;
	@Autowired
	private MpJsticketService mpJsticketService;
	

	private String getJsticket(String appid, String secret) throws DevMException{
		String access_token = mpAccessTokenSevice.getAccessToken(appid, secret);
		return mpJsticketService.getJsticket(access_token);
	}

	/**
	 * 获取JSSDK初始化使用的签名参数
	 * @param appid
	 * @param secret
	 * @param url
	 * @return
	 */
	public JSSDKSignResult getSignParam(String appid, String secret, String url)  throws DevMException{
		String nonce_str = RandomUtils.randomCustomUUID();
		Long timestamp = System.currentTimeMillis();
		String jsapi_ticket = getJsticket(appid, secret);
		// 注意这里参数名必须全部小写，且必须有序
		String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url="
				+ url;
		MessageDigest crypt = null;
		try {
			crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			String signature = byteToHex(crypt.digest());
			
			JSSDKSignResult param = new JSSDKSignResult();
			param.setAppId(appid);
			param.setNonceStr(nonce_str);
			param.setSignature(signature);
			param.setTimestamp(timestamp);
			return param;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}
}
